import request from '@/api/request'

// 文件上传相关接口

/**
 * 初始化上传会话
 */
export interface UploadInitRequest {
  fileName: string
  fileSize: number
  fileSha256: string
  chunkSize: number
  parentId?: number
  mimeType?: string
}

export interface UploadInitResponse {
  uploadId: string
  needUpload: boolean
  uploadedChunks: number[]
  chunkSize: number
  totalChunks: number
  existingFile?: {
    id: number
    fileName: string
    url: string
  }
}

export const initUpload = async (data: UploadInitRequest) => {
  try {
    console.log('🚀 发送初始化上传请求:', data)
    const response = await request.post<UploadInitResponse>('/files/upload/init', data)
    console.log('✅ 初始化上传响应:', response)
    return response
  } catch (error) {
    console.error('❌ 初始化上传请求失败:', error)
    throw error
  }
}

/**
 * 上传分片
 */
export const uploadChunk = (
  uploadId: string, 
  chunkIndex: number, 
  formData: FormData,
  config?: any
) => {
  return request.post(
    `/files/upload/chunk/${uploadId}/${chunkIndex}`,
    formData,
    {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      ...config
    }
  )
}

/**
 * 合并分片
 */
export interface MergeChunksRequest {
  uploadId: string
  fileName: string
  parentId?: number
}

export const mergeChunks = (data: MergeChunksRequest) => {
  return request.post('/files/upload/merge', data)
}

// 文件管理相关接口

/**
 * 获取文件列表
 */
export interface FileListParams {
  parentId?: number
  page?: number
  size?: number
  search?: string
  orderBy?: string
  orderDirection?: 'asc' | 'desc'
}

export interface FileInfo {
  id: number
  fileName: string
  originalName: string
  fileSize: number
  mimeType: string
  isDirectory: boolean
  parentId: number
  ownerId: number
  createdAt: string
  updatedAt: string
  thumbnailUrl?: string
  downloadUrl?: string
  canEdit: boolean
  canDelete: boolean
}

export interface FileListResponse {
  content: FileInfo[]
  totalElements: number
  totalPages: number
  currentPage: number
  storageInfo: {
    used: number
    quota: number
    percentage: number
  }
}

export const getFileList = (params: FileListParams) => {
  return request.get<FileListResponse>('/files', { params })
}

/**
 * 下载文件（兼容性接口，推荐使用 smartDownloadFile）
 */
export const downloadFile = (fileId: number) => {
  return request.get(`/files/${fileId}/download`, {
    responseType: 'blob'
  })
}

/**
 * 智能下载文件（推荐使用）
 * 自动选择最优下载方式
 */
export const smartDownloadFile = async (fileId: number, fileName: string) => {
  const { smartDownloadFile: smartDownload } = await import('./fileUrl')
  return smartDownload(fileId, fileName)
}

/**
 * 获取图片预览
 */
export const getImagePreview = (fileId: number) => {
  return request.get(`/preview/image/${fileId}`, {
    responseType: 'blob'
  })
}

/**
 * 获取PDF预览
 */
export const getPdfPreview = (fileId: number) => {
  return request.get(`/preview/pdf/${fileId}`, {
    responseType: 'blob'
  })
}

/**
 * 获取视频预览
 */
export const getVideoPreview = (fileId: number) => {
  return request.get(`/preview/video/${fileId}`, {
    responseType: 'blob'
  })
}

/**
 * 创建文件夹
 */
export interface CreateFolderRequest {
  folderName: string
  parentId?: number
}

export const createFolder = (data: CreateFolderRequest) => {
  return request.post<FileInfo>('/files/folder', data)
}

/**
 * 删除文件
 */
export const deleteFile = (fileId: number) => {
  return request.delete(`/files/${fileId}`)
}

/**
 * 重命名文件
 */
export interface RenameFileRequest {
  newName: string
}

export const renameFile = (fileId: number, data: RenameFileRequest) => {
  return request.put<FileInfo>(`/files/${fileId}/rename`, data)
}

/**
 * 移动文件
 */
export interface MoveFileRequest {
  targetParentId: number
}

export const moveFile = (fileId: number, data: MoveFileRequest) => {
  return request.put<FileInfo>(`/files/${fileId}/move`, data)
}

/**
 * 批量删除文件
 */
export const batchDeleteFiles = (fileIds: number[]) => {
  return request.delete('/files/batch', {
    data: { fileIds }
  })
}

/**
 * 批量移动文件
 */
export interface BatchMoveRequest {
  fileIds: number[]
  targetParentId: number
}

export const batchMoveFiles = (data: BatchMoveRequest) => {
  return request.put('/files/batch/move', data)
}

/**
 * 搜索文件
 */
export interface SearchFilesParams {
  keyword: string
  fileType?: string
  parentId?: number
  page?: number
  size?: number
}

export const searchFiles = (params: SearchFilesParams) => {
  return request.get<FileListResponse>('/files/search', { params })
}

/**
 * 获取文件详情
 */
export const getFileDetail = (fileId: number) => {
  return request.get<FileInfo>(`/files/${fileId}`)
}

/**
 * 获取文件夹路径
 */
export interface BreadcrumbItem {
  id: number
  name: string
  parentId?: number
}

export const getFolderPath = (folderId?: number) => {
  const url = folderId ? `/files/path/${folderId}` : '/files/path'
  return request.get<BreadcrumbItem[]>(url)
}

/**
 * 检查文件名是否存在
 */
export interface CheckFileNameRequest {
  fileName: string
  parentId?: number
}

export const checkFileName = (data: CheckFileNameRequest) => {
  return request.post<{ exists: boolean }>('/files/check-name', data)
}

/**
 * 获取存储统计信息
 */
export interface StorageStats {
  totalFiles: number
  totalFolders: number
  totalSize: number
  usedSpace: number
  availableSpace: number
  fileTypeStats: {
    type: string
    count: number
    size: number
  }[]
}

export const getStorageStats = () => {
  return request.get<StorageStats>('/files/stats')
}

/**
 * 获取最近文件
 */
export const getRecentFiles = (limit: number = 10) => {
  return request.get<FileInfo[]>('/files/recent', {
    params: { limit }
  })
}

/**
 * 获取收藏文件
 */
export const getFavoriteFiles = (params: FileListParams) => {
  return request.get<FileListResponse>('/files/favorites', { params })
}

/**
 * 添加/移除收藏
 */
export const toggleFavorite = (fileId: number) => {
  return request.post(`/files/${fileId}/favorite`)
}

/**
 * 获取回收站文件
 */
export const getTrashFiles = (params: FileListParams) => {
  return request.get<FileListResponse>('/files/trash', { params })
}

/**
 * 恢复文件
 */
export const restoreFile = (fileId: number) => {
  return request.post(`/files/${fileId}/restore`)
}

/**
 * 彻底删除文件
 */
export const permanentDeleteFile = (fileId: number) => {
  return request.delete(`/files/${fileId}/permanent`)
}

/**
 * 清空回收站
 */
export const emptyTrash = () => {
  return request.delete('/files/trash/empty')
}

/**
 * 复制文件到指定文件夹
 */
export const copyFileToFolder = (fileId: number, folderId: number) => {
  return request.post<FileInfo>(`/files/${fileId}/copy-to/${folderId}`)
}

/**
 * 复制文件到根目录
 */
export const copyFileToRoot = (fileId: number) => {
  return request.post<FileInfo>(`/files/${fileId}/copy-to-root`)
}

/**
 * 移动文件到指定文件夹
 */
export const moveFileToFolder = (fileId: number, folderId: number) => {
  return request.put<FileInfo>(`/files/${fileId}/move-to/${folderId}`)
}

/**
 * 移动文件到根目录
 */
export const moveFileToRoot = (fileId: number) => {
  return request.put<FileInfo>(`/files/${fileId}/move-to-root`)
}

/**
 * 高级搜索
 */
export interface AdvancedSearchParams {
  keyword?: string
  fileType?: string
  mimeType?: string
  minSize?: number
  maxSize?: number
  sizeUnit?: string
  startDate?: string
  endDate?: string
  parentId?: number
  page?: number
  size?: number
}

export const advancedSearch = (params: AdvancedSearchParams) => {
  return request.get<FileListResponse>('/files/advanced-search', { params })
}

/**
 * 取消上传
 */
export const cancelUpload = (uploadId: string) => {
  return request.delete(`/files/upload/${uploadId}/cancel`)
}
